<?php
namespace Company\Controller;
use Think\Controller;
class ImportaozhouController extends BaseController {
	public function _initialize()
    {
        parent::_initialize();
        $g=session('company');
        $db_name=$g['db'];
        $this->product = M('product',C('DB_PREFIX_T'), C('DB_TYPE') . '://' . C('DB_USER') . ':' . C('DB_PWD') . '@' . C('DB_HOST') . ':' . C('DB_PORT') . '/' . $db_name);
		//数据库连接基础配置-begin
		C('db_config.DB_TYPE',C('DB_TYPE'));
		C('db_config.DB_HOST',C('DB_HOST'));
		C('db_config.DB_USER',C('DB_USER'));
		C('db_config.DB_PWD',C('DB_PWD'));
		C('db_config.DB_PORT',C('DB_PORT'));
		C('db_config.DB_CHARSET',C('DB_CHARSET'));
		C('db_config.DB_NAME',$db_name);
		//数据库连接基础配置-end
    }
	
	//导入订单
	function doimportPushorder(){
		$param = I('param.','','trim');
		$owner_status=session('company.owner_status');//货主属性0:否1是
		if(!$owner_status){//不是货主（主erp）
			$order=A('order');
			$order->is_owner($param['username'],$param['warehouse_code']);
		}
		$trans = M('',C('DB_PREFIX_T'), C('db_config'));
        $trans->startTrans();   // 开启事务
		$m=M('Pushorder',C('DB_PREFIX_T'), C('db_config'));
		$g=M('Pushordergoods',C('DB_PREFIX_T'), C('db_config'));
		$p=M('Printorder',C('DB_PREFIX_T'), C('db_config'));
		$pro=M('Product',C('DB_PREFIX_T'), C('db_config'));
		$u=M('User');
		//$region=M('Region');
		//商家编码--begin
			$merchant_code=C('base_config.merchant_code');//商家编码
		//商家编码--end
		
		if(!empty($_FILES)){
			$config = array(
				'maxSize'    =>    3145728,    
				'savePath'   =>    '/Import/',
				'saveName'   =>    array('uniqid',''),    
				'exts'       =>    array('xlsx', 'xls'),    
				'autoSub'    =>    true,    
				'subName'    =>    array('date','Ymd'),);
			$upload = new \Think\Upload($config);// 实例化上传类
			$info   =   $upload->upload();
			if(!$info) {// 上传错误提示错误信息      
				$return['status']=0;
				$return['message']=$upload->getError();
				$this->ajaxReturn($return);    
			}
			$extension=$info['import']['ext'];
			// vendor("PHPExcel.PHPExcel");
			//导入PHPExcel类库，因为PHPExcel没有用命名空间，只能inport导入
			import("Org.Util.PHPExcel");
			import("Org.Util.PHPExcel.Writer.Excel5");
			import("Org.Util.PHPExcel.Writer.Excel2007");
			import("Org.Util.PHPExcel.IOFactory.php");
			
			//创建PHPExcel对象，注意，不能少了\
			$objPHPExcel = new \PHPExcel();
			
			$file_name='./Uploads'.$info['import']['savepath'].$info['import']['savename'];
			// dump($file_name);
			// die;
			if($extension=='xlsx'){
				$objReader = \PHPExcel_IOFactory::createReader('Excel2007');
			}
			if($extension=='xls'){
				$objReader = \PHPExcel_IOFactory::createReader('Excel5');
			}
			$objPHPExcel = $objReader->load($file_name,$encode='utf-8');

			$sheet = $objPHPExcel->getSheet(0);
			$highestRow = $sheet->getHighestRow(); // 取得总行数
			if($highestRow>500){
				alert_json(0,'最大只能导500条数据！');
			}
			$highestColumn = $sheet->getHighestColumn(); // 取得总列数
			// $sql = 'truncate table '.$db_name.'.'.C('DB_PREFIX_T').'arrival_order';
			// $stat=M()->execute($sql);//清空表
			$outbound=A('Outbound');
			if(empty($param['username'])){
				$username=session('company.username');
			}else{
				$username=$param['username'];
			}
			$warehouse_code=$param['warehouse_code'];

			$order_foreachcount=0;
			if($highestRow==1){
				alert_json(0,'没有数据！');
			}
			$total_order_tax=0;//全部税金
			
			for($i=2;$i<=$highestRow;$i++)
			{
				$data=array();
				$data_og=array();
				$print_order=array();
				
				$order_no		= $objPHPExcel->getActiveSheet()->getCell("B".$i)->getValue();//订单编号
				// dump($order_no);dump($old_order_no);
				if(empty($order_no) && empty($old_order_no)){
					$trans->rollback();
					alert_json(0,$i行."没有订单号！");
				}
				if(!empty($order_no) && !empty($old_order_no)){
					$order_foreachcount++;
				}
				if(empty($order_no) && !empty($old_order_no)){
					$order_no=$old_order_no;
				}
				//流水订单号-begin
				//流水单号兼容事务提交-begin
				// dump($serialNumber);
				$serialNumber_first=$outbound->serialNumber('Pushorder',$username,$warehouse_code);
				$len=strlen($serialNumber_first);
				$ser_nums=intval($serialNumber_first);
				$int_len=strlen($ser_nums);
				// $ser_nums=$ser_nums+$order_foreachcount;
				$str_nums="";
				for($j=0;$j<$len-$int_len;$j++){
					$str_nums.='0';
				}
				$serialNumber=$str_nums.$ser_nums;
				//流水单号兼容事务提交-end
				$serialNumber='P'.date("Ymd",time()).$serialNumber;
				//流水订单号-end
				
				$data['warehouse_code']=I('warehouse_code');
				$data['order_no']=$serialNumber;//流水单号
				$data['old_order_no']=$order_no;//原单号
				if($order_no!=$old_order_no){//不重复
					//重复判断--beging
					$m_info=$m->where(array('old_order_no'=>$order_no))->find();
					if(!empty($m_info)){
						$trans->rollback();
						$return['status']=0;
						$return['message']=$m_info['old_order_no']."要导入的订单编号已经存在！";
						$this->ajaxReturn($return);
					}else{
						$total_price=0;//订单总价格
					}
					//重复判断-end
				}
				$data['user_name']		= $objPHPExcel->getActiveSheet()->getCell("E".$i)->getValue();
				if($data['user_name'] instanceof \PHPExcel_RichText) { //富文本转换字符串
                    $data['user_name'] = $data['user_name']->__toString();
					$data['user_name']=trim($data['user_name']);
                }
				
				$data['user_phone']		= $objPHPExcel->getActiveSheet()->getCell("J".$i)->getValue();
				if($data['user_phone'] instanceof \PHPExcel_RichText) { //富文本转换字符串
                    $data['user_phone'] = $data['user_phone']->__toString();
					$data['user_phone']=trim($data['user_phone']);
                }
				
				$data['user_idcard']	= $objPHPExcel->getActiveSheet()->getCell("P".$i)->getValue();
				
				$data['province']		= $objPHPExcel->getActiveSheet()->getCell("F".$i)->getValue();
				if($data['province'] instanceof \PHPExcel_RichText) { //富文本转换字符串
                    $data['province'] = $data['province']->__toString();
                }
				$data['province']=trim($data['province']);
				
				$data['city']			= $objPHPExcel->getActiveSheet()->getCell("G".$i)->getValue();
				if($data['city'] instanceof \PHPExcel_RichText) { //富文本转换字符串
                    $data['city'] = $data['city']->__toString();
                }
				$data['city']=trim($data['city']);
				
				$data['area']			= $objPHPExcel->getActiveSheet()->getCell("H".$i)->getValue();
				if($data['area'] instanceof \PHPExcel_RichText) { //富文本转换字符串
                    $data['area'] = $data['area']->__toString();
                }
				$data['area']=trim($data['area']);
				
				$data['user_address']	= $objPHPExcel->getActiveSheet()->getCell("I".$i)->getValue();
				if($data['user_address'] instanceof \PHPExcel_RichText) { //富文本转换字符串
                    $data['user_address'] = $data['user_address']->__toString();
                }
				$data['user_address']=trim($data['user_address']);
				
				$data['buyer_name']	= $objPHPExcel->getActiveSheet()->getCell("Q".$i)->getValue();//购买人姓名
				if($data['buyer_name'] instanceof \PHPExcel_RichText) { //富文本转换字符串
                    $data['buyer_name'] = $data['buyer_name']->__toString();
					$data['buyer_name'] = trim($data['buyer_name']);
                }
				$data['add_time']		= time();

				$data_og['bar_code']	= $objPHPExcel->getActiveSheet()->getCell("L".$i)->getValue();
				if(is_object($data_og['bar_code'])){
					$data_og['bar_code']=$data_og['bar_code']->__toString();
					$data_og['bar_code']=trim($data_og['bar_code']);
				}
				if(empty($data_og['bar_code'])){
					$trans->rollback();
					$return['status']=0;
					$return['message']=$i."行编码为空，总共".$highestRow."行，请核对数据，并删除空行！";
					$this->ajaxReturn($return);
				}
				
				if($data['user_idcard'] instanceof \PHPExcel_RichText) { //富文本转换字符串
                    $data['user_idcard'] = $data['user_idcard']->__toString();
					$data['user_idcard'] = trim($data['user_idcard']);
                }
				if(empty($data['user_idcard'])){
					$trans->rollback();
					$return['status']=0;
					$return['message']=$i."行身份证号不能为空";
					$this->ajaxReturn($return);
				}
				if(strlen(trim($data['user_idcard']))!=18){
					$trans->rollback();
					$return['status']=0;
					$return['message']="第".$i."行身份证号不等于18位";
					$return['error']=strlen($data['user_idcard']);
					$this->ajaxReturn($return);
				}
				
				// $data_og['goods_price']	= $objPHPExcel->getActiveSheet()->getCell("M".$i)->getValue();
				// if(empty($data_og['goods_price'])){
					// $data_og['goods_price']=$goods_info['price'];
				// }
				$data_og['goods_no']	=$merchant_code.$data_og['bar_code'];//商品编码
				$goods_info=$pro->where(array('goods_no'=>$data_og['goods_no']))->find();
				$data_og['goods_price']=$goods_info['price'];
				if(empty($goods_info)){
					$trans->rollback();
					$return['status']=0;
					$return['message']="账册中没有查到对应条码信息【".$data_og['bar_code']."】";
					$this->ajaxReturn($return);
				}else{
					if($goods_info['examined']==1){
						$trans->rollback();
						$return['status']=0;
						$return['message']="【".$data_og['bar_code']."】未审核通过";
						$this->ajaxReturn($return);
					}
					if(empty($goods_info['pn'])){
						$trans->rollback();
						$return['status']=0;
						$return['message']="账册中没有查到对应条码信息【".$data_og['bar_code']."】对应的料号信息，请完善信息后再导入";
						$this->ajaxReturn($return);
					}
					// if(empty($data_og['goods_price'])){
						// if(empty($goods_info['price'])){
							// $trans->rollback();
							// $return['status']=0;
							// $return['message']="账册中没有查到对应条码信息【".$data_og['bar_code']."】对应的单价，请完善信息后再导入";
							// $this->ajaxReturn($return);
						// }else{
							// $data_og['goods_price']=$goods_info['price'];
						// }
					// }
					if(empty($goods_info['net_weight'])){
						$trans->rollback();
						$return['status']=0;
						$return['message']="账册中没有查到对应条码信息【".$data_og['bar_code']."】对应的净重，请完善信息后再导入";
						$this->ajaxReturn($return);
					}
					if(empty($goods_info['gross_weight'])){
						$trans->rollback();
						$return['status']=0;
						$return['message']="账册中没有查到对应条码信息【".$data_og['bar_code']."】对应的毛重，请完善信息后再导入";
						$this->ajaxReturn($return);
					}
					if(empty($goods_info['goods_tax'])){
						$trans->rollback();
						$return['status']=0;
						$return['message']="账册中没有查到对应条码信息【".$data_og['bar_code']."】对应的税率，请完善信息后再导入";
						$this->ajaxReturn($return);
					}
				}
				
				$data_og['goods_name']	= $objPHPExcel->getActiveSheet()->getCell("N".$i)->getValue();
				if($data_og['goods_name'] instanceof \PHPExcel_RichText) { //富文本转换字符串
                    $data_og['goods_name'] = $data_og['goods_name']->__toString();
					$data_og['goods_name'] = trim($data_og['goods_name']);
                }
				if(empty($data_og['goods_name'])){
					$trans->rollback();
					$return['status']=0;
					$return['message']= "商品名称不能为空";
					$this->ajaxReturn($return);
				}
				
				$data_og['goods_nums']	= $objPHPExcel->getActiveSheet()->getCell("O".$i)->getValue();
				if(is_object($data_og['goods_nums'])){
					$data_og['goods_nums']=$data_og['goods_nums']->__toString();
					$data_og['goods_nums']=trim($data_og['goods_nums']);
				}
				if($data_og['goods_nums']>10000000){
					$trans->rollback();
					$return['status']=0;
					$return['message']= "商品数量大于10000000，请校对后重新导入";
					$this->ajaxReturn($return);
				}
				if(empty($data_og['goods_nums'])){
					$trans->rollback();
					$return['status']=0;
					$return['message']= $i."行 共".$highestRow."行 商品数量不能为空";
					$this->ajaxReturn($return);
				}

				$print_order['receiveMan']=$objPHPExcel->getActiveSheet()->getCell("E".$i)->getValue();
				if(is_object($print_order['receiveMan'])){
					$print_order['receiveMan']=$print_order['receiveMan']->__toString();
					$print_order['receiveMan']=trim($print_order['receiveMan']);
				}
				$print_order['receiveManPhone']=$objPHPExcel->getActiveSheet()->getCell("J".$i)->getValue();
				if(is_object($print_order['receiveManPhone'])){
					$print_order['receiveManPhone']=$print_order['receiveManPhone']->__toString();
					$print_order['receiveManPhone']=trim($print_order['receiveManPhone']);
				}
				$print_order['receiveProvince']=$objPHPExcel->getActiveSheet()->getCell("F".$i)->getValue();
				if(is_object($print_order['receiveProvince'])){
					$print_order['receiveProvince']=$print_order['receiveProvince']->__toString();
					$print_order['receiveProvince']=trim($print_order['receiveProvince']);
				}
				$print_order['receiveCity']=$objPHPExcel->getActiveSheet()->getCell("G".$i)->getValue();
				if(is_object($print_order['receiveCity'])){
					$print_order['receiveCity']=$print_order['receiveCity']->__toString();
					$print_order['receiveCity']=trim($print_order['receiveCity']);
				}
				$print_order['receiveCounty']=$objPHPExcel->getActiveSheet()->getCell("H".$i)->getValue();
				if(is_object($print_order['receiveCounty'])){
					$print_order['receiveCounty']=$print_order['receiveCounty']->__toString();
					$print_order['receiveCounty']=trim($print_order['receiveCounty']);
				}
				$print_order['receiveManAddress']=$objPHPExcel->getActiveSheet()->getCell("I".$i)->getValue();
				if(is_object($print_order['receiveManAddress'])){
					$print_order['receiveManAddress']=$print_order['receiveManAddress']->__toString();
					$print_order['receiveManAddress']=trim($print_order['receiveManAddress']);
				}
				
				$print_order['txLogisticID']=$objPHPExcel->getActiveSheet()->getCell("B".$i)->getValue();
				if(is_object($print_order['txLogisticID'])){
					$print_order['txLogisticID']=$print_order['txLogisticID']->__toString();
					$print_order['txLogisticID']=trim($print_order['txLogisticID']);
				}
				$print_order['order_no']=$serialNumber;
				
				$print_order['add_time']=time();//添加时间

				if($order_no!=$old_order_no){//不重复
					$data['erp_mark_mailno']	= $objPHPExcel->getActiveSheet()->getCell("R".$i)->getValue();//订单备注(兼容赠品)
					if(is_object($data['erp_mark_mailno'])){
						$data['erp_mark_mailno']=$data['erp_mark_mailno']->__toString();
						$data['erp_mark_mailno']=trim($data['erp_mark_mailno']);
					}
					//添加订单
					$insert_id=$m->add($data);
					// echo $m->getError();
					// die;
					if(!$insert_id){
						$trans->rollback();
						alert_json(0,'添加订单数据失败');
					}
					//添加订单详情
					$data_og['order_id']=$insert_id;
					$res_g=$g->add($data_og);
					if(!$res_g){
						$trans->rollback();
						alert_json(0,'添加订单详情失败');
					}
					//添加面单
					$res_p=$p->add($print_order);
					if(!$res_p){
						$trans->rollback();
						alert_json(0,'添加面单数据失败');
					}
				}else{//重复
					//添加订单详情
					$data_og['order_id']=$insert_id;
					$res_g=$g->add($data_og);
					if(!$res_g){
						$trans->rollback();
						alert_json(0,'订单重复');
					}
				}
				$old_order_no=$order_no;
				$push_data['detail'][$i-2]['goods_detail_id']=$res_g;//商品详细id
				$push_data['detail'][$i-2]['goods_nums']=$data_og['goods_nums'];//数量
				$push_data['detail'][$i-2]['goods_no']=$data_og['goods_no'];//商品编码
				
				
				$order_tax=0;//订单总税金
				$goods_price=sprintf("%.2f",$data_og['goods_price']*$data_og['goods_nums']);//商品总价格=单价*数量
				file_put_contents('./log/goods_price.log',date('Y-m-d H:i:s').var_export($data_og['goods_price'],true).PHP_EOL,FILE_APPEND);//日志导出sql
				// $goods_tax=sprintf("%.2f",$goods_price*$goods_info['goods_tax']);//税金=商品总价格*税率
				$ems_fee=0;//运费
				$insure_amount=0;//保费
				$consumption_rate=$goods_info['consumption_rate'];//消费税率
				$increment_rate=$goods_info['increment_rate'];//增值税率
				$goods_tax=total_tax($goods_price,$ems_fee,$insure_amount,$consumption_rate,$increment_rate);//税金
				$total_price+=$goods_price;//总价格(不含税)
				if($total_price>=2000){
					$trans->rollback();
					alert_json(0,'总价格['.$total_price.']'.$data['old_order_no']."订单总金额不能大于2000");
				}
				$order_tax+=$goods_tax;//订单总税金
				$total_order_tax+=$goods_tax;//全部税金
			}
			$api_url="http://www.t-cang.com/oms/index.php/Api/ErpApi/frozen_money";//保证金扣费预估接口
			$api_url_un="http://www.t-cang.com/oms/index.php/Api/ErpApi/unfreeze_money";//保证金扣费预估(释放金额)接口
			
			$u_info=$u->where(array('username'=>$username))->find();
			
			$api_push_data['customer']['user_code']=$u_info['user_code'];
			$api_push_data['customer']['user_key']=$u_info['user_key'];
			$api_push_data['data']['order_tax']=$total_order_tax;
			$api_res=push($api_url,$api_push_data);

			$api_res=json_decode($api_res,true);
			file_put_contents('./log/order_tax.log',date('Y-m-d H:i:s').var_export($api_push_data,true).PHP_EOL,FILE_APPEND);//日志导出sql
			if(!$api_res['flag']){
				$trans->rollback();
				alert_json(0,$api_res['tip']);
			}

			//扣库存-begin
			// $push_data['warehouse_code']='12345678';//仓库编码
			// $push_data['warehouse_code']='11330213';//仓库编码(下沙仓)
			$push_data['warehouse_code']=I('warehouse_code');
			$url=C('base_config.freez_storage');
			if(empty($url)){
				alert_json(0,'请配置冻结库存接口');
			}
			$res_edit=push($url,$push_data);
			$res_edit=json_decode($res_edit,true);
			file_put_contents('./log/freez_storage.log',date('Y-m-d H:i:s').var_export($res_edit,true).PHP_EOL,FILE_APPEND);//日志导出sql
			if(!$res_edit['status']){
				//释放冻结金额-begin
					$api_res_un=push($api_url_un,$api_push_data);
				//释放冻结金额-end
				$trans->rollback();
				alert_json(0,$res_edit['message']);
			}else{
				foreach($res_edit['detail'] as $kss=>$vss){
					$map_p['id']=$vss['goods_detail_id'];//订单明细对应商品id
					$data_p['goods_batch_no']=$vss['str'];//关联批次和数量
					//$data_p['goods_batch_no']=array('exp',"concat(goods_batch_no,',$str')");//关联批次和数量
					$g->where($map_p)->save($data_p);
				}
			}
			//扣库存-end
			$trans->commit();
			$return['status']=1;
			$return['message']="导入成功！";
			$this->ajaxReturn($return);
		}else
		{
			$return['status']=0;
			$return['message']="请选择上传的文件!";
			$this->ajaxReturn($return);
		}
	}
	
}
